package com.jianganming.singleton;

import java.io.Serializable;
import java.util.Objects;

/**
 * 饿汉式
 * 特点：类加载时就初始化，线程安全
 */
public class Singleton implements Serializable {
    private static Singleton singleton = new Singleton();

    //防止反射破坏标志
    private static boolean singletonFlag = false;

    private Singleton(){
        //防止反射破坏
        if(Objects.nonNull(singleton) || singletonFlag){
            throw new RuntimeException("反射失败");
        }
        singletonFlag = true;
    }

    public static Singleton getInstance(){
        return singleton;
    }

    /**
     * 解决反序列化破坏单例
     * 请执行Deserialize.java代码测试
     * @return
     */
    private Object readResolve(){
        return singleton;
    }

    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance==instance1);
    }

}
